<?php
namespace Common\Model;
use Think\Model;
class StoremanagerModel extends Model {
        // protected $tablePrefix = '';
		protected $tableName  ='storemanager';
    /**
     * 获取当前加盟店的列表 返回一条记录
     * [getStores description]
     * @param  [type] $nowx [description]
     * @param  [type] $nowy [description]
     * @return [type]       [description]
     */
    public function getStores($nowx,$nowy,$allow_total=0){
    	$inforesult = M('storemanager')->where("is_valid=1")->select();
    	$infocount =count($inforesult);
    	$res=array();
        for($i=0;$i<$infocount;$i++){
            $latitude=$inforesult[$i]['lat'];
            $longitude=$inforesult[$i]['lng'];
            if($nowx!='' && $nowy!='' && $latitude!='' && $longitude!=''){
                $res[$i]['faraway'] = $this->get_distance($nowx,$nowy,$latitude,$longitude);
                $res[$i]['id'] = $inforesult[$i]['id'];
            }
        }
        if(!is_array($res)){
            return "";
        }
        $newlocallist = multi_array_sort($res, 'faraway', $sort = SORT_ASC);

        $nearList=array();$num=0;
        foreach($newlocallist as $v){
            $nearList[$num]=M('storemanager')->where("id=".$v['id'])->find();
            $nearList[$num]['distance']=$v['faraway'];
            $num++;
            if($num>$allow_total) return $nearList;
        }
        return $nearList;
    }




	public function get_distance($lat1, $lng1, $lat2, $lng2) {
        //将角度转为狐度
        $radLat1 = deg2rad($lat1);
        $radLat2 = deg2rad($lat2);
        $radLng1 = deg2rad($lng1);
        $radLng2 = deg2rad($lng2);
        $a = $radLat1 - $radLat2; //两纬度之差,纬度<90
        $b = $radLng1 - $radLng2; //两经度之差纬度<180
        //$s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2))) * 6378.137;
		$s = 6378.138*2*asin(sqrt(pow(sin( ($lat1*pi()/180-$lat2*pi()/180)/2),2)+cos($lat1*pi()/180)*cos($lat2*pi()/180)* pow(sin( ($lng1*pi()/180-$lng2*pi()/180)/2),2)));
        return round($s, 2);
    }
}